<?php

namespace app\api\controller\permission;

use app\api\controller\common\ApiBase;
use app\api\model\Admin as AdminModel;
use app\api\model\AdminRole as AdminRoleModel;
use think\Db;
use app\api\model\Organization as OrganizationModel;

class Admin extends ApiBase
{

    /**
     * 查看管理员
     *
     * @return void
     */
    public function index()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $orgId = isset($post['org_id']) && $post['org_id'] != '' ? $post['org_id'] : 0;
            $pageSize = isset($post['page_size']) && $post['page_size'] != '' ? $post['page_size'] : 10;
            $where['is_super'] = 0;
            if ($orgId != 0) {
                // $where['a.org_id'] = $orgId;
                $where[] = ['exp', Db::raw('FIND_IN_SET(' . $orgId . ',a.org_id_tree)')];
            }
            if (isset($post['keyword']) && $post['keyword'] != '') {
                $where['a.account|a.realname'] = ['like', '%' . $post['keyword'] . '%'];
            }
            $adminList = AdminModel::alias('a')
                ->with('role')
                ->join('crm_store b', 'b.id = a.org_id', 'LEFT')
                ->where($where)
                ->field('a.id,a.account,a.realname,a.mobile,a.email,a.org_id,b.title as org_name,a.create_time,a.update_time,a.max_number')
                ->paginate($pageSize);
            $list = $adminList->toArray();
            unset($list['per_page'], $list['last_page']);
            return json(array('code' => '1', 'msg' => '成功', 'data' => $list));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 管理员详情
     *
     * @return void
     */
    public function detail()
    {
        if (request()->isPost()) {
            $id = input('post.id');
            $where['id'] =  $id;
            $admin = AdminModel::where($where)->field('id,account,realname,mobile,email,org_id,create_time,update_time,max_number')->find();
            return json(array('code' => '1', 'msg' => '成功', 'data' => $admin));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 新增管理员
     *
     * @return void
     */
    public function add()
    {
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $admin = new AdminModel();
                $password = isset($post['password']) && $post['password'] != '' ? $post['password'] : '123456';
                $salt = substr(md5(uniqid(true)), 0, 4);
                $data['account'] = isset($post['account']) && $post['account'] != '' ? $post['account'] : '';
                $data['password'] = md5(md5($password) . $salt);
                $data['salt'] = $salt;
                $data['realname'] = isset($post['realname']) && $post['realname'] != '' ? $post['realname'] : '';
                $data['mobile'] = isset($post['mobile']) && $post['mobile'] != '' ? $post['mobile'] : '';
                $data['email'] = isset($post['email']) && $post['email'] != '' ? $post['email'] : '';
                $data['org_id'] = isset($post['org_id']) && $post['org_id'] != '' ? $post['org_id'] : 0;
//                $data['max_number'] = isset($post['max_number']) && $post['max_number'] != '' ? $post['max_number'] : 30;
                $data['is_super'] = 0;
                $data['org_id_tree'] = $post['org_id'];
                $parentOrgId = $post['org_id'];
                do {
                    $p = OrganizationModel::where(['id' => $parentOrgId])->field('parent_id')->find();
                    $parentOrgId = $p['parent_id'];
                    $data['org_id_tree'] = $parentOrgId . ',' . $data['org_id_tree'];
                } while ($parentOrgId > 0);
                $result = $admin->validate('Admin.add')->save($data);
                if (false === $result) {
                    $msg = $admin->getError();
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => $msg));
                } else {
                    if (!empty($post['role_ids'])) {
                        $roleIds = explode(',', $post['role_ids']);
                        $admin->role()->save($roleIds);
                    }
                    Db::commit();
                    return json(array('code' => '1', 'msg' => '成功'));
                }
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 编辑管理员
     *
     * @return void
     */
    public function edit()
    {
        if (request()->isPost()) {
        Db::startTrans();
        try {
            $post = input('post.');
            $id = $post['id'];
            $admin = AdminModel::get($id);
            $password = isset($post['password']) && $post['password'] != '' ? $post['password'] : '';
            $data['account'] = isset($post['account']) && $post['account'] != '' ? $post['account'] : '';
            if($password){
                if(strlen($password)<6){
                    return json(array('code' => '0', 'msg' => '请输入大于6位数密码'));
                }



                $salt = substr(md5(uniqid(true)), 0, 4);
                $data['password'] = md5(md5($password) . $salt);
                $data['salt'] = $salt;
            }
            $data['realname'] = isset($post['realname']) && $post['realname'] != '' ? $post['realname'] : '';
            $data['mobile'] = isset($post['mobile']) && $post['mobile'] != '' ? $post['mobile'] : '';
            $data['email'] = isset($post['email']) && $post['email'] != '' ? $post['email'] : '';
            $data['org_id'] = isset($post['org_id']) && $post['org_id'] != '' ? $post['org_id'] : 0;
//            $data['max_number'] = isset($post['max_number']) && $post['max_number'] != '' ? $post['max_number'] : 30;
            $data['org_id_tree'] = $post['org_id'];
            $parentOrgId = $post['org_id'];
            do {
                $p = OrganizationModel::where(['id' => $parentOrgId])->field('parent_id')->find();
                $parentOrgId = $p['parent_id'];
                $data['org_id_tree'] = $parentOrgId . ',' . $data['org_id_tree'];
            } while ($parentOrgId > 0);
            $result = $admin->validate('Admin.edit')->save($data, ['id' => $id]);
            if (false === $result) {
                $msg = $admin->getError();
                Db::rollback();
                return json(array('code' => '0', 'msg' => $msg));
            } else {
                AdminRoleModel::where(['admin_id' => $id])->delete();
                if (!empty($post['role_ids'])) {
                    $roleIds = explode(',', $post['role_ids']);
                    $admin->role()->save($roleIds);
                }
                Db::commit();
                return json(array('code' => '1', 'msg' => '成功'));
            }
        } catch (\Exception $e) {
            Db::rollback();
            return json(array('code' => '0', 'msg' => $e->getMessage()));
        }
    } else {
        return json(array('code' => '0', 'msg' => '请求失败'));
    }
    }

    /**
     * 删除管理员
     *
     * @return void
     */
    public function del()
    {
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $id = input('post.id');
                $admin = AdminModel::get($id);
                $result = $admin->where(['id' => $id])->delete();
                if (false === $result) {
                    $msg = $admin->getError();
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => $msg));
                } else {
                    AdminRoleModel::where(['admin_id' => $id])->delete();
                    Db::commit();
                    return json(array('code' => '1', 'msg' => '成功'));
                }
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 批量删除
     *
     * @return void
     */
    public function batchDel()
    {
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $ids = input('post.ids');
                $where['is_super'] = 0;
                $where['id'] = ['in', $ids];
                $result = AdminModel::where($where)->delete();
                if (false === $result) {
                    $msg = AdminModel::getError();
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => $msg));
                } else {
                    AdminRoleModel::where(['admin_id' => ['in', $ids]])->delete();
                    Db::commit();
                    return json(array('code' => '1', 'msg' => '成功'));
                }
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 组织列表
     *
     * @return void
     */
    public function indexOrg()
    {
        if (request()->isPost()) {
            $orgList = OrganizationModel::field('id,org_name,parent_id,create_time,update_time')->select();
            $orgList = collection($orgList)->toArray();
            $orgList = list_to_tree($orgList);
            return json(array('code' => '1', 'msg' => '成功', 'data' => $orgList));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 新增组织
     *
     * @return void
     */
    public function addOrg()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $org = new OrganizationModel();
            $data['org_name'] = isset($post['org_name']) && $post['org_name'] != '' ? $post['org_name'] : '';
            $data['parent_id'] = isset($post['parent_id']) && $post['parent_id'] != '' ? $post['parent_id'] : 0;
            $result = $org->validate('Organization.add')->save($data);
            if (false === $result) {
                $msg = $org->getError();
                return json(array('code' => '0', 'msg' => $msg));
            } else {
                return json(array('code' => '1', 'msg' => '成功'));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 编辑组织
     *
     * @return void
     */
    public function editOrg()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $id = $post['id'];
            $org = OrganizationModel::get($id);
            $data['org_name'] = isset($post['org_name']) && $post['org_name'] != '' ? $post['org_name'] : '';
            $data['parent_id'] = isset($post['parent_id']) && $post['parent_id'] != '' ? $post['parent_id'] : 0;
            $result = $org->validate('Organization.edit')->save($data);
            if (false === $result) {
                $msg = $org->getError();
                return json(array('code' => '0', 'msg' => $msg));
            } else {
                return json(array('code' => '1', 'msg' => '成功'));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 删除组织
     *
     * @return void
     */
    public function delOrg()
    {
        if (request()->isPost()) {
            $id = input('post.id');
            $whereAdmin[] = ['exp', Db::raw('FIND_IN_SET(' . $id . ',org_id_tree)')];
            $admins = AdminModel::where($whereAdmin)->select();
            if ($admins) {
                return json(array('code' => '0', 'msg' => '该组织下已绑定管理员，不能直接删除'));
            }
            $children = OrganizationModel::where(['parent_id' => $id])->select();
            if (count($children) > 0) {
                return json(array('code' => '0', 'msg' => '该组织下有子组织，不能直接删除'));
            }
            $org = OrganizationModel::get($id);
            $result = $org->delete();
            if (false === $result) {
                $msg = $org->getError();
                return json(array('code' => '0', 'msg' => $msg));
            } else {
                return json(array('code' => '1', 'msg' => '成功'));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }
}
